package com.yifeng.repo.apm.endpoint.console.proxy;

import com.yifeng.repo.apm.endpoint.utils.BaseUtil;
import next.fire.spinus.logx.utils.http.HttpConnector;
import next.fire.spinus.logx.utils.http.HttpConnectorFactory;
import next.fire.spinus.logx.utils.http.HttpNotConnectionException;
import next.fire.spinus.logx.utils.http.HttpResult;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by daibing on 2020/12/8
 */
public class CommonProxy {
    private static final HttpConnectorFactory CONNECTOR_FACTORY = new HttpConnectorFactory();
    private static final String AUTH_TOKEN_HEADER_KEY = "X-SC-AccessToken";
    protected final String logConfUrl;
    protected final String logAccessToken;
    protected final int clientTimeoutMillis;

    public CommonProxy(String logConfUrl, String logAccessToken, int clientTimeoutMillis) {
        this.logConfUrl = logConfUrl;
        this.logAccessToken = logAccessToken;
        this.clientTimeoutMillis = clientTimeoutMillis;
    }

    protected HttpResult invoke(String url, String json, int timeoutMillis, String accessToken) {
        try {
            Map<String, String> header = new HashMap<String, String>();
            if (BaseUtil.isNotBlank(accessToken)) {
                header.put(AUTH_TOKEN_HEADER_KEY, accessToken);
            }
            HttpConnector conn = CONNECTOR_FACTORY.getConnector(url, timeoutMillis);
            return conn.sendWithHeader("POST", header, json);
        } catch (HttpNotConnectionException e) {
            throw e;
        } catch (Throwable t) {
            throw new RuntimeException(t.getClass().getName());
        }
    }

}
